$(function(){
  var updateDurations = function(durations){
    var gabc = $('#editor').val(),
        header = getHeader(gabc);
    isRecording = false;
    for(var i=0,c=0; i < durations.length && (i+c) < svg.timings.length; ++i) {
      while((i+c) < svg.timings.length && !svg.timings[i+c]) {
        ++c;
      }
      if(svg.timings[i+c]) {
        svg.timings[i+c] = {length: durations[i]/400};
      }
    }
    durations = durations.join(' ');
    header.cValues.timing = durations;
    $('#editor').val(header + gabc.slice(header.original.length));
    console.info(durations);
  };
  
  var lastDate = 0,
      durations = [],
      punctumID = 0,
      isRecording = false,
      recordWithSound = false;
      callback = function() {
        if(!isRecording) return;
        var date = new Date(),
            duration = lastDate? (date - lastDate) : 0;
        lastDate = date;
        if(duration) durations.push(duration);
        if(!svg.tones[punctumID]) {
          updateDurations(durations);
          return;
        }
        while(!svg.tones[punctumID].isPlayable()) {
          ++punctumID;
          if(!svg.tones[punctumID]) {
            updateDurations(durations);
            return;
          }
        }
        if(recordWithSound) svg.tones[punctumID].play();
        ++punctumID;
      };
  
  $(window).keydown(function(){
    callback();
  });
  var record = function(withSound) {
    lastDate = 0;
    durations = [];
    punctumID = 0;
    isRecording = true;
    recordWithSound = (withSound == true);
  };
  var load = function(load){
    if(load){
      $.get('../get.php?file=engravings/square/'+load,function(data){
        location.hash='#square/'+load;
        if(load.slice(-5)=='.gabc') {
          $('#txtLoad').val(load);
          $('#editor').val(data).keyup();
        }
      });
    }
  };
  var loadSelect = function(e,ui){
    if(ui.item.value.slice(-1)=='/') {
      $(this).autocomplete('search',ui.item.value);
    } else {
      load(ui.item.value);
    }
  };
  var windowResized = function(){
    var $cp = $("#chant-parent2");
    var totalHeight = $(window).height() - $cp.position().top - 18;
    $cp.height(totalHeight);
  };

  $('#txtLoad').each(function(){
    var $this = $(this);
    var discrepancy = $this.outerWidth(false) - $this.width();
    $this.width($this.parent().width() - $($this.prop('labels')).width() - discrepancy);
  });
  $('#txtLoad').click(function(){$(this).autocomplete('search');}).autocomplete({
    source: "../ac.php?root=engravings/square/&extension=gabc",
    select: loadSelect,
    minLength: 0
  });
  $("#lnkPlayScore").click(function(e){playScore(true);e.preventDefault();});
  $(window).resize(windowResized);
  setTimeout(windowResized,50);
  
  var regex = /(square)\/(.+)$/;
  var match = regex.exec(location.hash.slice(1));
  if(match) {
    $('#txtLoad').val(match[2]);
    load(match[2]);
  }
  window['record'] = record;
});